// web/src/app/api/(learn)/course/[courseId]/chapters/route.ts
import {NextRequest, NextResponse} from "next/server";
import {currentUser} from "@/lib/auth";
import {db} from "@/lib/db";

export async function POST(
    req: NextRequest,
    {params}: { params: { courseId: string } }
) {
    try {
        const user = await currentUser()
        if (!user) return new NextResponse('Unauthorized', {status: 401})
        const {title} = await req.json()

        const courseOwner = await db.course.findUnique({
            where: {
                id: params.courseId,
                userId: user.id
            }
        })

        if (!courseOwner) {
            return new NextResponse('Unauthorized', {status: 401})
        }

        const lastChapter = await db.chapter.findFirst({
            where: {
                courseId: params.courseId
            },
            orderBy: {
                position: 'desc'
            }
        })

        const newPosition = lastChapter ? lastChapter.position + 1 : 1

        const chapter = await db.chapter.create({
            data: {
                title, courseId: params.courseId, position: newPosition
            }
        })

        return NextResponse.json(chapter)
    } catch (e) {
        console.error('[CHAPTERS]', e)
        return new NextResponse('Internal Server Error', {status: 500})
    }
}